package Interview.gensuixue;

import java.util.HashMap;
import java.util.Map;

/**
 * 最长不重复子串
 * @author leiwenkang
 * @date 2020/4/11
 */
public class Test01最长不重复子串 {
    public static void main(String[] args) {
        String str = "eabcdfaghce";
        System.out.println(getLongestStr(str));
    }
    public static int getLongestStr(String str) {
        if (str == null || str.length() == 0) {
            return 0;
        }

        int curLength = 0;
        int maxLength = 0;
        Map<Character, Integer> map = new HashMap<>();

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (map.containsKey(ch)) {
                int distance = i - map.get(ch);
                if (distance > curLength) {
                    curLength++;
                } else {
                    curLength = distance;
                }
            } else {
                curLength++;
            }

            if (curLength > maxLength) {
                maxLength = curLength;
            }
            map.put(ch, i);
        }
        return maxLength;
    }
}
